package cn.com.hhrcw.sms.service;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

public class SendTest {
    private static final String appKey = "Zmgp1vfs";
    private static final String appSecret = "406c9f9d8fed8179bdfd73a80c4e87ece8d0a61e";

    public static void main(String [] arg){
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("appKey",appKey);
        treeMap.put("mobiles","18637109325");
        treeMap.put("smsContent","验证码：000999，5分钟内有效。欢迎登录黄河人才网！");
        treeMap.put("timestamp",String.valueOf(System.currentTimeMillis()));
        treeMap.put("nonce",uuid());
        treeMap.put("signatureMethod","HMAC-SHA1");
        String signature = getSignature(treeMap);
        treeMap.put("signature",signature);

        HttpResponse response = HttpUtil.createPost("https://ping.hn-talent.com/send/v1/sendSms").contentType("application/json").body(JSON.toJSONString(treeMap)).execute();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>"+response.body());
        SendResultVo resultVo = JSON.parseObject(response.body(),SendResultVo.class);
        System.out.println(">>>>>>>>>>>>>>>>>>>>> code "+ resultVo.getCode());
        System.out.println(">>>>>>>>>>>>>>>>>>>>>OK");
    }

    public static String uuid(){
        String s= UUID.randomUUID().toString();
        return s.replace("-", "");
    }

    public static String getSignature(TreeMap<String,String> treeMap){
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(appSecret.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            org.apache.commons.codec.binary.Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }


}
